<script setup>
import { computed } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import { useUserStore } from '@/stores/user'
import { logout as apiLogout } from '@/api/auth'

const router = useRouter()
const route = useRoute()
const userStore = useUserStore()

const activePath = computed(() => route.path)
// 认证页路径判定：以 /auth 前缀归类，显示轻量布局
const isAuthRoute = computed(() => route.path.startsWith('/auth'))

const menus = [
  {
    label: '挂号收费',
    children: [
      { label: '窗口挂号', path: '/register/counter' },
      { label: '窗口退号', path: '/register/refund' },
      { label: '收费', path: '/fee/charge' },
      { label: '退费', path: '/fee/refund' },
      { label: '费用记录查询', path: '/fee/log' },
    ],
  },
  {
    label: '医生工作',
    children: [
      { label: '患者查看', path: '/doctor/patient' },
      { label: '医生诊疗', path: '/doctor/diagnosis' },
      { label: '看诊记录', path: '/doctor/record' },
    ],
  },
  {
    label: '检查管理',
    children: [
      { label: '检查申请', path: '/check/request' },
      { label: '患者录入', path: '/check/patient' },
      { label: '检查录入', path: '/check/input' },
      { label: '结果管理', path: '/check/manage' },
    ],
  },
  {
    label: '检验管理',
    children: [
      { label: '检验申请', path: '/inspect/apply' },
      { label: '患者录入', path: '/inspect/patient' },
      { label: '检验录入', path: '/inspect/input' },
      { label: '结果管理', path: '/inspect/manage' },
    ],
  },
  {
    label: '药房管理',
    children: [
      { label: '药房发药', path: '/pharmacy/dispense' },
      { label: '药房退药', path: '/pharmacy/return' },
      { label: '药品管理', path: '/pharmacy/storage' },
      { label: '交易记录', path: '/pharmacy/records' },
    ],
  },
  { label: '处置管理',
    children: [
      { label: '处置申请', path: '/disposal/apply' },
      { label: '患者录入', path: '/disposal/patient' },
      { label: '处置录入', path: '/disposal/input' },
      { label: '结果管理', path: '/disposal/manage' },
    ],
  },
  { label: '系统管理',
    children: [
      { label: '科室管理', path: '/system/department' },
    ],
  }
]

// 判断菜单项是否禁用
function isMenuDisabled(item) {
  const role = userStore.role
  if (role === '管理员') return false
  if (role === '医生') {
    // 医生不能用挂号收费和系统管理
    if (
      item.path.startsWith('/register') ||
      item.path.startsWith('/fee') ||
      item.path.startsWith('/system')
    ) return true
  }
  if (role === '病人') {
    // 病人只能用挂号收费
    if (
      !item.path.startsWith('/register') &&
      !item.path.startsWith('/fee')
    ) return true
  }
  return false
}

// 菜单点击事件，禁用项不跳转
const handleSelect = (key) => {
  // 找到当前菜单项
  const item = menus.flatMap(g => g.children).find(i => i.path === key)
  if (item && isMenuDisabled(item)) return
  router.push(key)
}

// 点击左上角 LOGO 返回首页（BlankPage）
const handleLogoClick = () => {
  if (route.path !== '/') router.push('/')
}

// 退出登录：调用后端 /auth/logout，清空本地状态，跳转登录
const handleLogout = async () => {
  try {
    await apiLogout()
  } catch (e) { /* 忽略网络错误，仍执行本地退出 */ }
  userStore.logout()
  router.push('/auth/login')
}
</script>

<template>
  <div v-if="isAuthRoute" class="auth-only">
    <router-view />
  </div>
  <div v-else class="layout">
    <aside class="sider">
      <div class="logo" @click="handleLogoClick">
        <span class="logo-main">
          <span class="logo-his">HIS</span>
          <span class="logo-title">医院系统</span>
        </span>
      </div>
      <el-menu
        :default-active="activePath"
        class="menu"
        @select="handleSelect"
        router
      >
        <template v-for="(group, gi) in menus" :key="gi">
          <el-sub-menu :index="String(gi)">
            <template #title>
              <span>{{ group.label }}</span>
            </template>
            <el-menu-item
              v-for="item in group.children"
              :key="item.path"
              :index="item.path"
              :disabled="isMenuDisabled(item)"
              class="menu-item"
            >
              <span>{{ item.label }}</span>
            </el-menu-item>
          </el-sub-menu>
        </template>
      </el-menu>
    </aside>

    <section class="content">
      <header class="topbar">
        <div class="spacer"></div>
        <div class="user-box">
          <div class="avatar">{{ (userStore.username||'?').charAt(0).toUpperCase() }}</div>
          <div class="uname" title="当前登录用户">{{ userStore.username }}</div>
          <el-divider direction="vertical" />
          <el-button size="small" type="primary" @click="handleLogout" class="logout-btn">退出</el-button>
        </div>
      </header>
      <main class="page">
        <router-view />
      </main>
    </section>
  </div>
</template>

<style scoped>
.layout {
  display: flex;
  height: 100vh;
  background: linear-gradient(135deg, #e3f2fd 0%, #b3e5fc 100%);
}

.sider {
  width: 220px;
  background: linear-gradient(135deg, #e3f2fd 0%, #b3e5fc 100%);
  border-right: 1px solid #90caf9;
  display: flex;
  flex-direction: column;
  box-shadow: 2px 0 8px rgba(33, 150, 243, 0.08);
}

.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 24px;
  color: #1976d2;
  border-bottom: 1px solid #90caf9;
  cursor: pointer;
  user-select: none;
  letter-spacing: 2px;
  background: linear-gradient(90deg, #e3f2fd 60%, #b3e5fc 100%);
  transition: background .25s, color .25s;
}

.menu {
  border-right: none;
  flex: 1;
  background: transparent;
  --el-menu-bg-color: transparent;
  --el-menu-text-color: #1976d2;
  --el-menu-active-color: #039be5;
  --el-menu-hover-bg-color: #e1f5fe;
  --el-menu-item-height: 48px;
  font-size: 16px;
}
:deep(.el-menu-item) {
  border-radius: 8px !important;
  margin: 2px 8px;
  transition: background 0.2s, color 0.2s;
}
:deep(.el-menu-item.is-active) {
  background: linear-gradient(90deg, #039be5 60%, #b3e5fc 100%) !important;
  color: #fff !important;
}
:deep(.el-menu-item:hover) {
  background: #e1f5fe !important;
  color: #1976d2 !important;
}
:deep(.el-sub-menu__title) {
  color: #1976d2 !important;
  font-weight: 600;
  font-size: 17px;
  border-radius: 8px;
  margin: 2px 4px;
  transition: background 0.2s, color 0.2s;
}
:deep(.el-sub-menu__title:hover) {
  background: #e1f5fe !important;
  color: #1976d2 !important;
}

.content {
  flex: 1;
  display: flex;
  flex-direction: column;
  min-width: 0;
}

.topbar {
  height: 64px;
  display: flex;
  align-items: center;
  padding: 0 32px;
  border-bottom: 1px solid #90caf9;
  background: linear-gradient(90deg, #e3f2fd 60%, #b3e5fc 100%);
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.06);
}

.spacer { flex: 1; }

.page {
  padding: 28px;
  overflow: auto;
  flex: 1;
  background: transparent;
}

.auth-only { min-height: 100vh; }

/* 顶部用户信息美化（卡片式，带渐变和阴影） */
.user-box {
  display: flex;
  align-items: center;
  gap: 16px;
  font-size: 16px;
  background: linear-gradient(135deg, #e1f5fe 0%, #90caf9 100%);
  padding: 10px 28px 10px 18px;
  border-radius: 32px;
  box-shadow: 0 4px 16px #90caf9;
  border: 1px solid #b3e5fc;
  position: relative;
  min-width: 220px;
}
.user-box::before {
  content: "";
  position: absolute;
  left: 8px; top: 8px; right: 8px; bottom: 8px;
  border-radius: 24px;
  background: linear-gradient(90deg, #bbdefb 0%, #e3f2fd 100%);
  opacity: 0.18;
  z-index: 0;
}
.user-box > * { position: relative; z-index: 1; }

.user-box .avatar {
  width: 38px;
  height: 38px;
  border-radius: 50%;
  background: linear-gradient(135deg,#1976d2,#039be5 80%);
  display:flex;
  align-items:center;
  justify-content:center;
  color:#fff;
  font-weight:600;
  font-size: 20px;
  box-shadow:0 2px 8px -2px #90caf9;
  border: 2px solid #fff;
}
.user-box .uname {
  max-width: 120px;
  white-space: nowrap;
  overflow: hidden;
  text-overflow: ellipsis;
  font-weight:500;
  color: #1976d2;
  font-size: 16px;
  letter-spacing: 1px;
}
.user-box .logout-btn {
  --el-button-border-color: transparent;
  border-radius: 10px !important;
  background: linear-gradient(135deg, #039be5 0%, #64b5f6 100%) !important;
  color: #fff !important;
  font-weight: 500;
  font-size: 16px !important;
  box-shadow: 0 2px 8px #90caf9;
  padding: 0 18px;
  border: none !important;
}
.user-box .logout-btn:hover {
  background: linear-gradient(135deg, #1976d2 0%, #039be5 100%) !important;
  filter: brightness(1.08);
  color: #fff !important;
}

:deep(.el-divider) {
  background: #90caf9 !important;
  height: 28px !important;
  margin: 0 8px !important;
}

@media (max-width: 900px) {
  .layout { flex-direction: column; }
  .sider { width: 100vw; min-width: 0; flex-direction: row; border-right: none; border-bottom: 1px solid #90caf9; }
  .logo { height: 48px; font-size: 18px; }
  .menu { font-size: 15px; }
  .topbar { padding: 0 10px; height: 48px; }
  .page { padding: 10px; }
  .user-box { padding: 6px 10px 6px 8px; font-size: 13px; min-width: 0; gap: 8px; }
  .user-box .avatar { width: 28px; height: 28px; font-size: 15px; }
  :deep(.el-divider) { height: 18px !important; }
}
.logo {
  height: 60px;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 700;
  font-size: 26px;
  letter-spacing: 2px;
  background: linear-gradient(90deg, #e3f2fd 60%, #b3e5fc 100%);
  color: #1976d2;
  border-bottom: 1px solid #90caf9;
  cursor: pointer;
  user-select: none;
  transition: background .25s, color .25s;
  box-shadow: 0 2px 8px rgba(33, 150, 243, 0.04);
}
.logo-main {
  display: flex;
  align-items: center;
  gap: 8px;
}
.logo-his {
  font-size: 30px;
  font-weight: 900;
  background: linear-gradient(90deg, #26c6da 0%, #43a047 60%, #1976d2 100%);
  -webkit-background-clip: text;
  background-clip: text;
  color: transparent;
  text-shadow: 0 2px 12px #b2dfdb;
  letter-spacing: 3px;
  margin-right: 8px;
}
.logo-title {
  font-size: 20px;
  font-weight: 600;
  color: #1976d2;
  letter-spacing: 2px;
  text-shadow: 0 2px 8px #b2dfdb;
}
.logo:hover {
  background: #b3e5fc;
  color: #1565c0;
}
:deep(.el-menu-item.is-disabled) {
  color: #b0b0b0 !important;
  background: #f5f5f5 !important;
  cursor: not-allowed !important;
  opacity: 0.7;
}
</style>
